//
//  STSerSetVC.m
//  YiYueHairdresser
//
//  Created by zhouzhouzhou on 2018/9/30.
//  Copyright © 2018年 YuYiLian. All rights reserved.
//

#import "STSerSetVC.h"

#import "STSerSetView.h"
#import "STSerPackageView.h"
#import "TZImagePickerController.h"
#import "STTimerSelView.h"
#import "UploadManage.h"

@interface STSerSetVC ()<STSerSetViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,STTimerSelViewDelegate>{
    STSerSetView * serSetView;
    STTimerSelView * timerSelView;
    NSArray * arrSelTimers;
    NSMutableArray * arrActualTimes;
    //
    
    
    
    
}
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@end

@implementation STSerSetVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"服务设置";
    [self wr_setNavBarTintColor:[UIColor blackColor]];
    
    if(!self.serviceModel){
        self.serviceModel = [STServiceInfoModel new];
    }
    self.serviceModel.servicename = self.serName;
    self.serviceModel.categoryId = self.serviceTypeData.objectId;
    self.serviceModel.stylistId = [[YLUserInfo sharedInstance].stylistId longValue];
    
    [self createrIndividualSer];
    if(self.serviceId){
        [self loadServiceSetInfo];
    }
}

//查询服务
-(void)loadServiceSetInfo{
    WeakSelf
    [STHairService getBarberServerInfoWithServiceId:self.serviceId completion:^(id result, NSError *error) {
        if (error) {
            [ZYHCommonMethod showError:error];
        }
        self.serviceModel = [STServiceInfoModel modelWithJSON:result];
        if(!_serviceTypeData){
            [weakSelf loadCategoryInfo];
        }
        serSetView.isLoadData = YES;
        [self createrIndividualSer];
    }];
}

//类目详情
-(void)loadCategoryInfo{
    [STHairService getCategoryById:self.serviceModel.categoryId completion:^(id result, NSError *error) {
        if (error) {
            [ZYHCommonMethod showError:error];
        }
        _serviceTypeData = [STServiceCategoryModel modelWithJSON:result];
        serSetView.serviceTypeData = _serviceTypeData;
        [self createrIndividualSer];
    }];
}

//单项服务界面
-(void)createrIndividualSer{
    if(!serSetView){
        serSetView = [[STSerSetView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        serSetView.serviceTypeData = self.serviceTypeData;
        serSetView.serName = self.serName;
        serSetView.delegate = self;
        serSetView.serviceModel = self.serviceModel;
        [self.view addSubview:serSetView];
    }
    [serSetView setSerViewWithData:self.serviceModel];
}

//-(void)loadServiceListAndOptionsData{
//    [STHairService getCategoryById:self.categoryId packageType:0 completion:^(id result, NSError *error) {
//        if (error) {
//            [ZYHCommonMethod showError:error];
//        }else{
//
//        }
//    }];
//}

     
     
-(void)serSerSelTimer{
    arrSelTimers = @[@"0.5小时",@"1小时",@"1.5小时",@"2小时",@"2.5小时",@"3小时",@"3.5小时",@"4小时",@"4.5小时",@"5小时",@"5.5小时",@"6小时"];
    if (!timerSelView) {
        timerSelView = [[STTimerSelView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        timerSelView.delegate = self;
        [timerSelView setTimerSelectWithData:arrSelTimers];
    }
    [self.view addSubview:timerSelView];
}

-(void)serActualSerSelTimer:(NSInteger)num{
    arrActualTimes = [NSMutableArray arrayWithCapacity:0];
    arrActualTimes = (NSMutableArray *)[arrSelTimers subarrayWithRange:NSMakeRange(0, num+1)];
    STTimerSelView * actualTimerSelView = [[STTimerSelView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    //TODO:实际服务时间可以多选，开始和结束必选
    actualTimerSelView.delegate = self;
    actualTimerSelView.isMulti = YES;
    actualTimerSelView.selNums = [NSMutableArray arrayWithArray:@[@0,@(num)]];
    actualTimerSelView.unAbles = @[@0,@(num)];
    actualTimerSelView.titleStr = @"实际服务时间";
    [actualTimerSelView setTimerSelectWithData:arrActualTimes];
    [self.view addSubview:actualTimerSelView];
}


-(void)timerSelView:(STTimerSelView *)view  SeltectNum:(NSArray *)num{
    if(!num.count){
        return;
    }
    if([view isEqual:timerSelView]){
        int selNum = (int)[num.firstObject integerValue];
        NSString * selStr = arrSelTimers[selNum];
        NSString * timerStr = [selStr substringToIndex:(selStr.length-2)];
        self.serviceModel.duration =[timerStr floatValue]*60;
        [serSetView setNewSelTimer];
        if(selNum>=2){
            [self serActualSerSelTimer:selNum];
        }
        
    }else{
        NSMutableArray * arrTimer = [NSMutableArray arrayWithCapacity:num.count];
        for (NSString * selNumStr in num) {
            int selNum = (int)[selNumStr integerValue];
            NSString * selStr = arrSelTimers[selNum];
            NSString * timerStr = [selStr substringToIndex:(selStr.length-2)];
            [arrTimer addObject:timerStr];
        }
        NSString * lockStr = [arrTimer componentsJoinedByString:@","];
        self.serviceModel.locktime = lockStr;
    }
    serSetView.serviceModel =self.serviceModel;
    
}

-(void)serSelMainImg{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
    }];
    [alertVc addAction:takePhotoAction];
    UIAlertAction *imagePickerAction = [UIAlertAction actionWithTitle:@"去相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pushTZImagePickerController];
    }];
    [alertVc addAction:imagePickerAction];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertVc addAction:cancelAction];
    [self presentViewController:alertVc animated:YES completion:nil];
}

-(void)serSetSaveWithData:(STServiceInfoModel *)data{
    if(!data.mainImg){
        [ZYHCommonMethod showErrorAlertView:@"缺少主图"];
        return;
    }
    
    self.serviceModel = data;
    WeakSelf
    [[UploadManage manager] uploadPortraitWithImage:data.mainImg success:^(NSURLSessionTask *task, id responseObject) {
        NSDictionary * dicResult = [NSDictionary dictionaryWithDictionary:responseObject];
        if ([dicResult[@"code"] intValue] ==200) {
            NSString * imgUrl = dicResult[@"data"];
            weakSelf.serviceModel.picture = imgUrl;
            [weakSelf saveNewService];
        }else{
            [ZYHCommonMethod showErrorAlertView:dicResult[@"message"]];
        }
    } failure:^(NSURLSessionTask *task, NSError *error) {
        [ZYHCommonMethod showError:error];
    }];
}
    
-(void)saveNewService{
    NSDictionary * oldDic = [self.serviceModel modelToJSONObject];
    NSMutableDictionary * dicParameter = [NSMutableDictionary dictionaryWithCapacity:0];
    NSArray * allKeys = oldDic.allKeys;
    for (NSString * key in allKeys) {
        id value = oldDic[key];
        if([value isKindOfClass:[NSNumber class]]){
            NSNumber * valueNum = value;
            if ([key isEqualToString:@"categoryId"] || ![valueNum isEqualToNumber:@0]) {
                [dicParameter setObject:valueNum forKey:key];
            }
        }else{
            [dicParameter setObject:value forKey:key];
        }
    }
    int serviceType = 1;
    if(self.serviceTypeData.options.count){
        serviceType = 2;
    }
    NSMutableArray * arrNew = [NSMutableArray arrayWithCapacity:self.serviceModel.serviceOptions.count];
    for(STServiceOptionModel * oldModel in self.serviceModel.serviceOptions){
        for (STServiceOOModel * oomodel in oldModel.serviceOptionDetails) {
            STServiceOptionModel * newModel = [STServiceOptionModel new];
            if(oomodel){
                newModel.optionvalue = oomodel.optionvalue;
                newModel.price = oomodel.price;
                if(oomodel.serviceOptionId){
                    newModel.serviceOptionId = oomodel.serviceOptionId;
                }
            }
            newModel.optionId = oldModel.optionId;
            newModel.optionname  = oldModel.optionname;
            newModel.optiontitle = oldModel.optiontitle;
            if(!newModel.optionvalue){
                newModel.optionvalue = @"";
            }
            NSMutableDictionary * dicNew =[NSMutableDictionary dictionaryWithDictionary:[newModel modelToJSONObject]];
            //        NSNumber * spcId = ;
            if ([dicNew[@"serviceOptionId"] isEqualToNumber:@0]) {
                [dicNew removeObjectForKey:@"serviceOptionId"];
            }
            if ([dicNew[@"spcId"] isEqualToNumber:@0]) {
                [dicNew removeObjectForKey:@"spcId"];
            }
            if ([dicNew.allKeys containsObject:@"serviceOptionDetails"]) {
                [dicNew removeObjectForKey:@"serviceOptionDetails"];
            }
            [arrNew addObject:dicNew];
        }
    }
    
    [dicParameter setObject:@"zyh - 1" forKey:@"servicename"];
    [dicParameter setObject:@(serviceType) forKey:@"serviceType"];
    [dicParameter setObject:arrNew forKey:@"serviceOptions"];
    [dicParameter removeObjectForKey:@"mainImg"];
    [STHairService saveBarberServerWithParameters:dicParameter completion:^(id result, NSError *error) {
        if(error){
            [ZYHCommonMethod showError:error];
        }else{
            [ZYHCommonMethod showSuccess:@"保存成功"];
        }
    }];
}

//
-(void)actionChangeMainImg:(UIImage *)img{
    [serSetView setNewMainImg:img];
}

- (void)pushTZImagePickerController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:nil pushPhotoPickerVc:YES];
    WeakSelf
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        [weakSelf actionChangeMainImg:photos.lastObject];
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}




- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
}

// 调用相机
- (void)pushImagePickerController {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        _imagePickerVc.allowsEditing = YES;
        _imagePickerVc.sourceType = sourceType;
        [self presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
   
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    [tzImagePickerVc showProgressHUD];
    if ([type isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        [self actionChangeMainImg:image];
        // save photo and get asset / 保存图片，获取到asset
//        [[TZImageManager manager] savePhotoWithImage:image location:nil completion:^(PHAsset *asset, NSError *error){
//            [tzImagePickerVc hideProgressHUD];
//            if (error) {
//                NSLog(@"图片保存失败 %@",error);
//            } else {
//               [weakSelf actionChangeMainImg:image];
//            }
//        }];
    } else if ([type isEqualToString:@"public.movie"]) {
        NSLog(@"这是视频");
    }
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}
     
@end
